var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/tasks');

/**
 * 注册schema
 */ 
var Schema = mongoose.Schema;
var Tasks = new Schema({
  project: String,
  description: String
});
mongoose.model('Task', Tasks);

/**
 * 添加文档
 */ 
var Task = mongoose.model('Task');
var task = new Task(); 
task.project = 'Bikeshed';
task.description = 'Paint the bikeshed red.';
task.save(function(err) {
  if (err) throw err;
  console.log('Task saved.');
});

/**
 * 搜索文档
 */ 
var Task = mongoose.model('Task');
Task.find({'project': 'Bikeshed'}, function(err, tasks) {
  for (var i = 0; i < tasks.length; i++) {
    console.log('ID:' + tasks[i]._id);
    console.log(tasks[i].description);
  }
});

/**
 * 更新文档
 */ 
var Task = mongoose.model('Task');
Task.update(
  {_id: '55b76c60ccf4cea910440dd9'}, // 用内部ID更新
  {description: 'Paint the bikeshed green.'},
  {multi: false}, // 只更新一个文档
  function(err, rows_updated) {
    if (err) throw err;
    console.log('Updated.');
  }
);

/**
 * 删除文档
 */
var Task = mongoose.model('Task');
Task.findById('55b76df3d39d44eb10a5062f', function(err, task) {
  task.remove();
});

/**
 * 关闭连接
 */ 
//mongoose.disconnect(); // 注: 必须回调结束后才能关闭，否则操作还没完成就已关闭连接
